package pers.huangyuhui.sms.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import pers.huangyuhui.sms.util.CreateVerifiCodeImage;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class OutVerificationCodeController {

    @GetMapping("generateVerificationCode.do")
    protected void generateLoginVerifyCode(HttpSession session, HttpServletResponse response) {

        // 获取验证码信息
        BufferedImage verifyCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        String verifyCode = String.valueOf(CreateVerifiCodeImage.getVerifiCode());

        // 存储验证码Session
        session.setAttribute("rightCode", verifyCode);
//        System.out.println(verifyCode);

        // 设置响应内容类型
        response.reset();
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 将验证码图片输出到登录页面
        try {
            ImageIO.write(verifyCodeImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}